<template>
  <div class="upload-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="title">文件上传</h1>
      <p class="subtitle">请上传您的身份证照片或简历文件</p>
    </div>

    <!-- 上传表单 -->
    <div class="upload-form">
      <!-- 文件类型选择 -->
      <div class="form-group">
        <label for="fileType">文件类型</label>
        <div class="radio-group">
          <label class="radio-label">
            <input type="radio" v-model="fileType" value="idcard" />
            <span class="radio-custom"></span>
            <span class="radio-text">身份证照片</span>
          </label>
          <label class="radio-label">
            <input type="radio" v-model="fileType" value="resume" />
            <span class="radio-custom"></span>
            <span class="radio-text">简历文件</span>
          </label>
        </div>
      </div>

      <!-- 文件选择区域 -->
      <div class="file-upload-area" @click="handleClickUpload">
        <input type="file" ref="fileInput" @change="handleFileChange" accept="image/*,.pdf,.doc,.docx" />

        <!-- 上传区域内容 -->
        <div v-if="!selectedFile" class="upload-placeholder">
          <div class="upload-icon">
            <i class="fa fa-cloud-upload"></i>
          </div>
          <p class="upload-text">点击或拖拽文件到此处上传</p>
          <p class="upload-hint">支持 JPG、PNG、PDF、DOC、DOCX 格式</p>
        </div>

        <!-- 已选择文件预览 -->
        <div v-else class="upload-preview">
          <div class="preview-thumbnail" v-if="isImage">
            <img :src="previewUrl" alt="Preview" class="preview-image" />
          </div>
          <div class="preview-thumbnail" v-else>
            <div class="file-icon">
              <i :class="getFileIconClass()"></i>
            </div>
          </div>
          <div class="preview-info">
            <h3 class="file-name">{{ selectedFile.name }}</h3>
            <p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
            <button class="remove-btn" @click="removeFile">
              <i class="fa fa-times"></i> 移除
            </button>
          </div>
        </div>
      </div>

      <!-- 上传按钮 -->
      <div class="form-group submit-group">
        <button
          class="upload-btn"
          @click="uploadFile"
          :disabled="!selectedFile || isUploading"
        >
          <i class="fa fa-paper-plane"></i>
          <span>{{ isUploading ? '上传中...' : '开始上传' }}</span>
        </button>
      </div>
    </div>

    <!-- 已上传文件展示区域 -->
    <div v-if="uploadedFile" class="file-display-area">
      <h3 class="display-title">已上传文件</h3>
      <div class="display-content">
        <div v-if="isDisplayImage" class="display-item">
          <img :src="uploadedFile.url" alt="Uploaded File" class="display-image" />
        </div>
        <div v-else class="display-item">
          <div class="file-icon display-icon">
            <i :class="getDisplayFileIconClass()"></i>
          </div>
          <div class="file-info">
            <h4 class="file-display-name">{{ uploadedFile.name }}</h4>
            <a :href="uploadedFile.url" target="_blank" class="file-download">
              <i class="fa fa-download"></i> 下载文件
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传结果提示 -->
    <div v-if="uploadResult" class="result-message" :class="uploadResult.success ? 'success' : 'error'">
      <div class="message-icon">
        <i :class="uploadResult.success ? 'fa fa-check-circle' : 'fa fa-exclamation-circle'"></i>
      </div>
      <div class="message-content">
        <h3>{{ uploadResult.message }}</h3>
        <p v-if="uploadResult.success && uploadResult.url">
          <a :href="uploadResult.url" target="_blank">点击查看文件</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      fileType: 'idcard',  // 默认文件类型为身份证
      selectedFile: null,  // 选中的文件
      previewUrl: '',     // 文件预览URL
      isUploading: false, // 上传状态
      uploadResult: null, // 上传结果
      userId: localStorage.getItem('userId') || '', // 从本地存储获取用户ID
      uploadedFile: null, // 存储已上传的文件信息
    };
  },
  computed: {
    // 判断是否为图片文件
    isImage() {
      if (!this.selectedFile) return false;
      const imageTypes = ['image/jpeg', 'image/png', 'image/gif'];
      return imageTypes.includes(this.selectedFile.type);
    },
    // 判断展示文件是否为图片
    isDisplayImage() {
      if (!this.uploadedFile) return false;
      const imageTypes = ['image/jpeg', 'image/png', 'image/gif'];
      return imageTypes.includes(this.uploadedFile.type);
    }
  },
  methods: {
    // 点击上传区域
    handleClickUpload() {
      if (!this.isUploading) {
        this.$refs.fileInput.click();
      }
    },

    // 处理文件选择
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
        this.createFilePreview(file);
        this.uploadResult = null; // 重置上传结果
      }
    },

    // 创建文件预览
    createFilePreview(file) {
      if (this.isImage) {
        this.previewUrl = URL.createObjectURL(file);
      } else {
        // 非图片文件使用默认图标
        this.previewUrl = '';
      }
    },

    // 移除已选择的文件
    removeFile() {
      this.selectedFile = null;
      this.previewUrl = '';
      this.$refs.fileInput.value = '';
    },

    // 获取文件图标类
    getFileIconClass() {
      if (!this.selectedFile) return 'fa fa-file';

      const fileExt = this.selectedFile.name.split('.').pop().toLowerCase();
      switch (fileExt) {
        case 'pdf': return 'fa fa-file-pdf-o';
        case 'doc':
        case 'docx': return 'fa fa-file-word-o';
        case 'xlsx':
        case 'xls': return 'fa fa-file-excel-o';
        case 'ppt':
        case 'pptx': return 'fa fa-file-powerpoint-o';
        default: return 'fa fa-file';
      }
    },

    // 获取展示文件的图标类
    getDisplayFileIconClass() {
      if (!this.uploadedFile) return 'fa fa-file';

      const fileExt = this.uploadedFile.name.split('.').pop().toLowerCase();
      switch (fileExt) {
        case 'pdf': return 'fa fa-file-pdf-o';
        case 'doc':
        case 'docx': return 'fa fa-file-word-o';
        case 'xlsx':
        case 'xls': return 'fa fa-file-excel-o';
        case 'ppt':
        case 'pptx': return 'fa fa-file-powerpoint-o';
        default: return 'fa fa-file';
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';

      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));

      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    // 上传文件
    async uploadFile() {
      if (!this.selectedFile || this.isUploading) return;

      this.isUploading = true;
      this.uploadResult = null;

      try {
        const formData = new FormData();
        formData.append('file', this.selectedFile);
        formData.append('type', this.fileType);

        const response = await axios.post(
          'http://127.0.0.1:8000/user/qiniuUpload/',
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (progressEvent) => {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              console.log(`上传进度: ${percentCompleted}%`);
            }
          }
        );
        // 自动调试打印后端返回内容和类型
        console.log('后端返回内容(axios):', response.data);
        console.log('后端返回类型(axios):', typeof response.data);

        // 上传成功后更新文件展示信息
        this.uploadedFile = {
          name: this.selectedFile.name,
          size: this.selectedFile.size,
          url: response.data.url,
          type: this.selectedFile.type
        };

        // 上传成功提示
        this.uploadResult = {
          success: true,
          message: '文件上传成功',
          url: response.data.url
        };

        // 上传成功后重置表单
        this.selectedFile = null;
        this.previewUrl = '';
        this.$refs.fileInput.value = '';
      } catch (error) {
        console.error('上传失败:', error);
        this.uploadResult = {
          success: false,
          message: error.response?.data?.error || '上传失败，请重试'
        };
      } finally {
        this.isUploading = false;
      }
    }
  }
};
</script>

<style scoped>
/* 原有样式... */
.upload-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Inter', sans-serif;
}

.page-header { text-align: center; margin-bottom: 20px; }
.title { font-size: 24px; margin-bottom: 8px; }
.subtitle { color: #666; font-size: 14px; }

.upload-form {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.form-group { margin-bottom: 15px; }
label { font-size: 14px; font-weight: 500; margin-bottom: 8px; }

.radio-group { display: flex; gap: 15px; }
.radio-custom { width: 18px; height: 18px; border: 2px solid #ddd; }
.radio-label input:checked + .radio-custom { border-color: #409eff; background-color: #409eff; }

.file-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 25px;
  text-align: center;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
}
.upload-icon { font-size: 36px; color: #409eff; margin-bottom: 10px; }
.upload-text { font-size: 16px; margin-bottom: 5px; }
.upload-hint { font-size: 12px; color: #999; }

.upload-preview { display: flex; gap: 15px; align-items: center; }
.preview-thumbnail { width: 60px; height: 60px; background-color: #f5f5f5; border-radius: 6px; display: flex; justify-content: center; align-items: center; }
.preview-image { max-width: 100%; max-height: 100%; }
.file-icon { font-size: 28px; }
.file-name { font-size: 14px; margin-bottom: 3px; }
.file-size { font-size: 12px; color: #666; margin-bottom: 0; }
.remove-btn { font-size: 12px; color: #f56c6c; padding: 0; }

.submit-group { text-align: center; margin-top: 20px; }
.upload-btn {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
}
.upload-btn:disabled { background-color: #ccc; cursor: not-allowed; }

.result-message {
  margin-top: 20px;
  padding: 12px 15px;
  border-radius: 6px;
  display: flex;
  align-items: center;
}
.message-icon { font-size: 20px; margin-right: 10px; }
.message-content h3 { font-size: 14px; margin: 0; }

/* 新增文件展示样式 */
.file-display-area {
  margin: 20px 0;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
}
.display-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}
.display-content { display: flex; gap: 15px; align-items: center; }
.display-item { flex: 1; }
.display-image { max-width: 100%; border-radius: 6px; }
.display-icon { font-size: 32px; }
.file-display-name { font-size: 14px; font-weight: 500; margin-bottom: 3px; }
.file-display-size { font-size: 12px; color: #666; margin-bottom: 8px; }
.file-download {
  color: #409eff;
  text-decoration: none;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
}

/* 移动端适配 */
@media (max-width: 576px) {
  .display-content { flex-direction: column; align-items: center; }
  .display-item { max-width: 100%; text-align: center; }
}
</style>